/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-21 08:39:50
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-29 11:12:04
 * @Description: 增、删、改操作 db日志中间件
 */
import { Context } from "egg";
// import { sysLogInterface } from "../model/sys/log";

export default (options) => {
  return async (ctx: Context, next) => {
    const startTime = Date.now();
    // console.log(options);
    if (options) {
    }

    // 不保存get的log
    if (ctx.method === "GET") {
      await next();
      return;
    }

    // getSearchData接口不进行log
    if (
      ctx.method === "POST" &&
      ctx.request.path.indexOf("/getSearchData") > -1
    ) {
      await next();
      return;
    }

    // 过滤某些接口白名单，不进行日志记录。
    const whiteList = ["/sys/user/login", "/sys/user/logout"];
    const isWhite = whiteList.some((item) => {
      return item === ctx.request.path;
    });

    if (isWhite) {
      await next();
      return;
    }

    let body = JSON.stringify(ctx.request.body);
    if (body.length > 2500) {
      body = "long body";
    }
    const params = {
      query: ctx.query,
      params: ctx.params,
      body,
    };

    // console.log("user will login");
    const logData = {
      type: 1,
      type_name: "crud",
      user_id: ctx.loginUserInfo?.uid || 0,
      user_name: ctx.loginUserInfo?.name || "",
      request_url: ctx.request.path,
      method: ctx.request.method,
      params: JSON.stringify(params),
      request_ip: ctx.request.ip,
      response_status: 0,
      result: "",
      app_status: "",
      user_agent: ctx.headers["user-agent"],
      time: 0,
    };

    await next();
    // console.log(ctx.body);

    logData.result = ctx.body?.msg; //login 输出的信息中msg
    logData.response_status = ctx.status;
    logData.app_status = ctx.body?.code;
    logData.time = Date.now() - startTime;
    // console.log(logData);
    // console.log(ctx.headers);
    // 写入数据库日志
    ctx.model.Sys.Log.create(logData);
  };
};
